package app;

import java.io.UnsupportedEncodingException;
import java.text.*;
import java.util.*;

import org.w3c.dom.*;


import utils.*;

public class TicketList implements RequestListener, HttpItemListener {
	public final static String DRIVER_NOTE = "DRIVER_NOTE";
	public final static String ADD_WATER_GAL = "ADD_WATER_GAL";
	public final static String STR_TIME_LEFT_PLANT = "STR_TIME_LEFT_PLANT";
	public final static String STR_TIME_ARRIVED_JOB = "STR_TIME_ARRIVED_JOB";
	public final static String STR_TIME_START_POUR = "STR_TIME_START_POUR";
	public final static String STR_TIME_FINISHED_POUR = "STR_TIME_FINISHED_POUR";
	public final static String STR_TIME_LEFT_JOB = "STR_TIME_LEFT_JOB";
	public final static String STR_TIME_ARRIVED_PLANT = "STR_TIME_ARRIVED_PLANT";
	public final static String STR_TIME_ELAPSED = "STR_TIME_ELAPSED";
	public final static String C_TIME_LEFT_PLANT = "C_TIME_LEFT_PLANT";
	public final static String C_TIME_ARRIVED_JOB = "C_TIME_ARRIVED_JOB";
	public final static String C_TIME_START_POUR = "C_TIME_START_POUR";
	public final static String C_TIME_FINISHED_POUR = "C_TIME_FINISHED_POUR";
	public final static String C_TIME_LEFT_JOB = "C_TIME_LEFT_JOB";
	public final static String C_TIME_ARRIVED_PLANT = "C_TIME_ARRIVED_PLANT";
	public final static String C_TIME_ELAPSED = "C_TIME_ELAPSED";
	public final static String ACCEPT_TERMS = "ACCEPT_TERMS";
	public final static String SIGN_NAME = "SIGN_NAME";
	public final static String SIGNATURE = "SIGNATURE";
	public final static String LOGO_URL = "LOGO_URL";
	public final static String PLANT_ADDR = "PLANT_ADDR";
	public final static String EMAILS = "EMAILS";
	public final static String CUSTOM_EMAILS = "CUSTOM_EMAILS";
	public final static String IS_GONING = "IS_GONING";
	public final static String CURRENT_TIME_INDEX = "CURRENT_TIME_INDEX";
	public final static String BATCH_WEIGHT = "BATCH_WEIGHT";
	public final static String HIDE_BATCH_WEIGHT = "HIDE_BATCH_WEIGHT";
	public final static String REJECT_NAME = "REJECT_NAME";
	public final static String REJECT_REASON = "REJECT_REASON";
	public final static String DONT_NEED_BW = "DONT_NEED_BW";

	
	public Vector<Dictionary<String, Object>> data;
	public Dictionary<Long, Dictionary<String, Object>> memoryObject;
	
	private Vector<RequestItem> get_logo_requests;
	private Vector<RequestItem> get_batchWeight_requests;
	private Vector<RequestItem> get_plat_addr_requests;
	private Vector<RequestItem> get_emails_requests;
	private RequestItem refresh_request;
	private HttpQueue normalQueue;
	private HttpItem bwc;
	private long bwid;
	
	public TicketList() {
		normalQueue = new HttpQueue();
		get_logo_requests = new Vector<RequestItem>();
		get_batchWeight_requests = new Vector<RequestItem>();
		get_plat_addr_requests = new Vector<RequestItem>();
		get_emails_requests = new Vector<RequestItem>();
		
		data = new Vector<Dictionary<String, Object>>();
		
		memoryObject = new Hashtable<Long, Dictionary<String, Object>>();
	}
	
	public void dealloc() {
		if (get_logo_requests != null) {
			for (int i = 0; i < get_logo_requests.size(); i++) {
				AppDelegate.sharedInstance().cancelRequest(get_logo_requests.elementAt(i));
			}
			get_logo_requests = null;
		}
		if (get_batchWeight_requests != null) {
			for (int i = 0; i < get_batchWeight_requests.size(); i++) {
				AppDelegate.sharedInstance().cancelRequest(get_batchWeight_requests.elementAt(i));
			}
			get_batchWeight_requests = null;
		}
		if (get_plat_addr_requests != null) {
			for (int i = 0; i < get_plat_addr_requests.size(); i++) {
				AppDelegate.sharedInstance().cancelRequest(get_plat_addr_requests.elementAt(i));
			}
			get_plat_addr_requests = null;
		}
		if (get_emails_requests != null) {
			for (int i = 0; i < get_emails_requests.size(); i++) {
				AppDelegate.sharedInstance().cancelRequest(get_emails_requests.elementAt(i));
			}
			get_emails_requests = null;
		}
		data = null;
		if (refresh_request != null) {
			AppDelegate.sharedInstance().cancelRequest(refresh_request);
			refresh_request = null;
		}
		if (normalQueue != null) {
			if (bwc != null) {
				normalQueue.cancel(bwc);
			}
			normalQueue = null;
		}
		bwc = null;
		bwid = 0;
	}
	
	public void refresh() {
		int request_num = 0;
		request_num += get_logo_requests.size();
		request_num += get_batchWeight_requests.size();
		request_num += get_plat_addr_requests.size();
		request_num += get_emails_requests.size();
		if (refresh_request != null) request_num += 1;
		if (bwc != null) request_num += 1;
		if (request_num == 0) {
			Dictionary<String, Object> param = new Hashtable<String, Object>();
			param.put("type", "refresh");
			refresh_request = AppDelegate.sharedInstance().sendHttpRequest("getTicketList?Truckid="+AppDelegate.sharedInstance().truckID, param, this);
		}
//		for (int i = 0; i < get_logo_requests.size(); i++) {
//			AppDelegate.sharedInstance().cancelRequest(get_logo_requests.elementAt(i));
//		}
//		for (int i = 0; i < get_batchWeight_requests.size(); i++) {
//			AppDelegate.sharedInstance().cancelRequest(get_batchWeight_requests.elementAt(i));
//		}
//		for (int i = 0; i < get_plat_addr_requests.size(); i++) {
//			AppDelegate.sharedInstance().cancelRequest(get_plat_addr_requests.elementAt(i));
//		}
//		for (int i = 0; i < get_emails_requests.size(); i++) {
//			AppDelegate.sharedInstance().cancelRequest(get_emails_requests.elementAt(i));
//		}
//		get_logo_requests.removeAllElements();
//		get_batchWeight_requests.removeAllElements();
//		get_plat_addr_requests.removeAllElements();
//		get_emails_requests.removeAllElements();
//		if (refresh_request != null) AppDelegate.sharedInstance().cancelRequest(refresh_request);
//		
//		if (bwc != null) {
//			normalQueue.cancel(bwc);
//			bwc = null;
//		}
//		bwid = 0;
//		
//		Dictionary<String, Object> param = new Hashtable<String, Object>();
//		param.put("type", "refresh");
//		refresh_request = AppDelegate.sharedInstance().sendHttpRequest("getTicketList?Truckid="+AppDelegate.sharedInstance().truckID, param, this);
	}

	public void saveCustomAndNotifyChange() {
		Dictionary<String, Object> temp = new Hashtable<String, Object>();
		temp.put("changed", new Vector<Long>());
		AppDelegate.sharedInstance().postNotification(DataSourceChangeNotificationListener.class, this, temp);
	}
	
	public void requestFinished(RequestItem request, Dictionary<String, Object> params,
			Element xml, boolean succ) {
		if ("refresh".equals(params.get("type"))) {
			refresh_request = null;
			Vector<Node> tickets = XMLReader.getNodeList(xml, "Tickets");
			Vector<Dictionary<String, Object>> ser = new Vector<Dictionary<String, Object>>();
			if (tickets != null) {
				for (int i = 0; i < tickets.size(); i++) {
					Element obj = (Element)tickets.elementAt(i);
					Dictionary<String, Object> sub = XMLReader.convert2Dictionary(obj);
					Vector<Dictionary<String, Object>> products = XMLReader.convert2Array(XMLReader.getNodeList(obj, "Products"));
					if (products != null) {
						sub.put("Products", products);
					}
					ser.addElement(sub);
				}
			}
			
			for (int i = 0; i < ser.size(); i++) {
				Dictionary<String, Object> dic = ser.elementAt(i);
				String date = (String) dic.get("Date");
				
				DateFormatSymbols a = new DateFormatSymbols(Locale.US);
				//a.setAmPmStrings(new String[] {"AM", "PM"});
				DateFormat format = new SimpleDateFormat("M/d/yyyy hh:mm:ss a", a);
				try {
					Date theDate = format.parse(date);
					long ctime = theDate.getTime();
					dic.put("ctime", Long.valueOf(ctime));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					dic.put("ctime", Long.valueOf(0));
				}
			}
			
			if (XMLReader.getIntForKey(xml, "ret", 0) == 1) {
				Vector<Long> changed = new Vector<Long>();
				for (int i = 0; i < ser.size(); i++) {
					Dictionary<String, Object> dic = ser.elementAt(i);
					long tickedIDi = IntConvert.parseLong((String) dic.get("TicketID"));
					boolean find = false;
					for (int j = 0; j < data.size(); j++) {
						Dictionary<String, Object> jd = data.elementAt(j);
						long tickedIDj = IntConvert.parseLong((String) jd.get("TicketID"));
						
						if (tickedIDi == tickedIDj) {
							data.setElementAt(dic, j);
							find = true;
							break;
						}
					}
					if (find == false) {
						data.addElement(dic);
					}
					changed.addElement(Long.valueOf(tickedIDi));
					
					if (memoryObject.get(Long.valueOf(tickedIDi)) == null) {
						memoryObject.put(Long.valueOf(tickedIDi), new Hashtable<String, Object>());
					}
				}
				
				for (int i = 0; i < data.size(); i++) {
					Dictionary<String, Object> dic = ser.elementAt(i);
					long ticketID = IntConvert.parseLong((String) dic.get("TicketID"));
					Dictionary<String, Object> c = memoryObject.get(Long.valueOf(ticketID));
					String logo = (String) c.get(LOGO_URL);
					if (logo == null) {
						Dictionary<String, Object> temp = new Hashtable<String, Object>();
						temp.put("ticketID", Long.valueOf(ticketID));
						temp.put("type", "getLogo");
						RequestItem get_logo_request = AppDelegate.sharedInstance().sendHttpRequest("getLogo?&ticketID="+ticketID, temp, this);
						get_logo_requests.add(get_logo_request);
					}
					
					String plat_addr = (String) c.get(PLANT_ADDR);
					if (plat_addr == null) {
						Dictionary<String, Object> temp = new Hashtable<String, Object>();
						temp.put("ticketID", Long.valueOf(ticketID));
						temp.put("type", "getPlatAdd");
						RequestItem get_plat_addr_request = AppDelegate.sharedInstance().sendHttpRequest("getPlantAdd?&ticketID="+ticketID, temp, this);
						get_plat_addr_requests.add(get_plat_addr_request);
					}
					
					Vector<String> emails = (Vector<String>)c.get(EMAILS);
					if (emails == null) {
						Dictionary<String, Object> temp = new Hashtable<String, Object>();
						temp.put("ticketID", Long.valueOf(ticketID));
						temp.put("type", "getEmails");
						RequestItem get_email = AppDelegate.sharedInstance().sendHttpRequest("getEmails?&ticketID="+ticketID, temp, this);
						get_emails_requests.add(get_email);
					}
					
					String address1 = (String) dic.get("DeliveryAddress1");
					String address2 = (String) dic.get("DeliveryAddress2");
					
					if (address1 == null) address1 = "";
					if (address2 == null) address2 = "";
					
					String address = address1 + " " + address2;
					dic.put("chj_address", address);
					
					GoogleMapDownloader.sharedInstance().downloadMap(address);
				}
				
				
				boolean haveBatchWeight = false;
				for (int i = 0; i < data.size(); i++) {
					Dictionary<String, Object> dic = ser.elementAt(i);
					if (IntConvert.parseInt((String) dic.get(DONT_NEED_BW)) == 0) {
						long ticketID = IntConvert.parseLong((String) dic.get("TicketID"));
						Dictionary<String, Object> c = memoryObject.get(Long.valueOf(ticketID));
						if (c.get(BATCH_WEIGHT) != null) {
							haveBatchWeight = true;
							break;
						}
					}
				}
				
				if (haveBatchWeight == false) {
					for (int i = 0; i < data.size(); i++) {
						Dictionary<String, Object> dic = ser.elementAt(i);
						if (IntConvert.parseInt((String) dic.get(DONT_NEED_BW)) == 0) {
							long ticketID = IntConvert.parseLong((String) dic.get("TicketID"));
							
							Dictionary<String, Object> temp = new Hashtable<String, Object>();
							temp.put("ticketID", Long.valueOf(ticketID));
							temp.put("type", "BATCH_WEIGHT");
							RequestItem batch_weight_request = AppDelegate.sharedInstance().sendHttpRequest("getBatchWeight?&ticketID="+ticketID, temp, this);
							get_batchWeight_requests.add(batch_weight_request);
						}
					}
				}
				
				Dictionary<String, Object> temp = new Hashtable<String, Object>();
				temp.put("changed", changed);
				AppDelegate.sharedInstance().postNotification(DataSourceChangeNotificationListener.class, this, temp);
			} else {
				WaittingAlertView waittingAlertView = WaittingAlertView.createWaittingAlertView();
				waittingAlertView.setTitle(XMLReader.getStringForKey(xml, "error", FilePack.getStringByID(STRING_ID.STR_ERROR_OCCUR)));
				waittingAlertView.show();
			}
		} else if ("getLogo".equals(params.get("type"))) {
			long ticketID = ((Long)params.get("ticketID")).longValue();
			if (XMLReader.getIntForKey(xml, "ret", 0) == 1) {
				Dictionary<String, Object> c = memoryObject.get(Long.valueOf(ticketID));
				if (c == null){
					c = new Hashtable<String, Object>();
					memoryObject.put(Long.valueOf(ticketID), c);
				}
				String logo = XMLReader.getStringForKey(xml, "logo", null);
				if (logo != null) {
					c.put(LOGO_URL, logo);

					Vector<Long> changed = new Vector<Long>();
					changed.addElement(Long.valueOf(ticketID));
					Dictionary<String, Object> temp = new Hashtable<String, Object>();
					temp.put("changed", changed);
					AppDelegate.sharedInstance().postNotification(DataSourceChangeNotificationListener.class, this, temp);
					ImageDownloader.sharedInstance().downloadImage(logo);
				}
			}
			get_logo_requests.removeElement(request);
		} else if ("getPlatAdd".equals(params.get("type"))) {
			long ticketID = ((Long)params.get("ticketID")).longValue();
			if (XMLReader.getIntForKey(xml, "Ret", 0) == 1) {
				Dictionary<String, Object> c = memoryObject.get(Long.valueOf(ticketID));
				if (c == null){
					c = new Hashtable<String, Object>();
					memoryObject.put(Long.valueOf(ticketID), c);
				}
				String plat_addr = XMLReader.getStringForKey(xml, "Address", null);
				if (plat_addr != null) {
					c.put(PLANT_ADDR, plat_addr);
					Vector<Long> changed = new Vector<Long>();
					changed.addElement(Long.valueOf(ticketID));
					Dictionary<String, Object> temp = new Hashtable<String, Object>();
					temp.put("changed", changed);
					AppDelegate.sharedInstance().postNotification(DataSourceChangeNotificationListener.class, this, temp);
				}
			}
			get_plat_addr_requests.removeElement(request);
		} else if ("getEmails".equals(params.get("type"))) {
			long ticketID = ((Long)params.get("ticketID")).longValue();
			if (XMLReader.getIntForKey(xml, "ret", 0) == 1) {
				Dictionary<String, Object> c = memoryObject.get(Long.valueOf(ticketID));
				if (c == null){
					c = new Hashtable<String, Object>();
					memoryObject.put(Long.valueOf(ticketID), c);
				}
				Vector<String> emails = XMLReader.convert2StringArray(XMLReader.getNodeList(xml, "emails"));
				if (emails != null) {
					c.put(EMAILS, emails);
					Vector<Long> changed = new Vector<Long>();
					changed.addElement(Long.valueOf(ticketID));
					Dictionary<String, Object> temp = new Hashtable<String, Object>();
					temp.put("changed", changed);
					AppDelegate.sharedInstance().postNotification(DataSourceChangeNotificationListener.class, this, temp);
				}
			}
			get_emails_requests.removeElement(request)
;		} else if ("BATCH_WEIGHT".equals(params.get("type"))) {
			long ticketID = ((Long)params.get("ticketID")).longValue();
			if (XMLReader.getIntForKey(xml, "ret", 0) == 1) {
				for (int i = 0; i < get_batchWeight_requests.size(); i++) {
					AppDelegate.sharedInstance().cancelRequest(get_batchWeight_requests.elementAt(i));
				}
				get_batchWeight_requests.removeAllElements();
				
				{
					String url = XMLReader.getStringForKey(xml, "Ticket", null);
					if (url != null) {
						if (url.equals("Hide")) {
							Dictionary<String, Object> c = memoryObject.get(Long.valueOf(ticketID));
							c.put(BATCH_WEIGHT, "");
							c.put(HIDE_BATCH_WEIGHT, "1");
							
							Vector<Long> changed = new Vector<Long>();
							changed.addElement(Long.valueOf(ticketID));
							Dictionary<String, Object> temp = new Hashtable<String, Object>();
							temp.put("changed", changed);

							WaittingAlertView alert = WaittingAlertView.createWaittingAlertView();
							alert.setTitle(FilePack.getStringByID(STRING_ID.STR_READY_TO_GO));
							alert.show();
						} else {
							Vector<Dictionary<String, String>> servers = LoginServer.sharedInstance().data;
							for (int i = 0; i < servers.size(); i++) {
								Dictionary<String, String> dic = servers.elementAt(i);
								
								String server = dic.get("url");
								
								if (dic.get("connected") != null) {
									url = server+"/"+url;
									break;
								}
							}
							
							bwid = ticketID;
							bwc = normalQueue.get(url, this, Long.valueOf(bwid), false);
							
						}
					}
				}

			}
			get_batchWeight_requests.removeElement(request);
		}
	}

	public void reqeuestFinished(byte[] byteArray, Element xml,
			boolean successfull, Object param) {
		if (bwid == ((Long)param).longValue()) {
			// TODO Auto-generated method stub
			if (successfull) {
				try {
					String txt = new String(byteArray, "UTF-8");
					Dictionary<String, Object> c = memoryObject.get(Long.valueOf(bwid));
					c.put(BATCH_WEIGHT, txt);
					
					Vector<Long> changed = new Vector<Long>();
					changed.addElement(Long.valueOf(bwid));
					Dictionary<String, Object> temp = new Hashtable<String, Object>();
					temp.put("changed", changed);
					AppDelegate.sharedInstance().postNotification(DataSourceChangeNotificationListener.class, this, temp);

					WaittingAlertView alert = WaittingAlertView.createWaittingAlertView();
					alert.setTitle(FilePack.getStringByID(STRING_ID.STR_READY_TO_GO));
					alert.show();
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
			}
			bwid = 0;
			bwc = null;
		}
	}
}
